package com.example.foodDemo.controller;

import com.example.foodDemo.bean.User;
import com.example.foodDemo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;

    /*用户登录*/
    @RequestMapping("/login")
    @ResponseBody
    public Map login(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();

        //根据User样板在数据库中查询,没查到则为空
        User findUser = userDao.findOne(Example.of(user)).orElse(null);

        //若查询到的findUser不为空,则登陆成功,否则登录失败
        if (findUser != null) {
            map.put("success", true);
            map.put("message", "登录成功");
            map.put("data", findUser);
        } else {
            map.put("success", false);
            map.put("message", "登录失败");
            map.put("data", null);
        }
        return map;
    }

    /*用户注册*/
    @RequestMapping("/register")
    @ResponseBody
    public Map register(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        System.out.println(user.toString());
        //根据User样板在数据库中查询,没查到则为空
        User findUser = userDao.findOne(Example.of(user)).orElse(null);
        
        //若查询到的findUser不为空,则注册成功,否则注册失败
        if (findUser == null) {
            User user1 = userDao.saveAndFlush(user);
            map.put("success", true);
            map.put("message", "注册成功");
            map.put("data", user1);
        } else {
            map.put("success", false);
            map.put("message", "用户已存在");
        }
        return map;
    }
}
